package com.airycode.distribution.distribution1.base;

import com.airycode.distribution.distribution1.constants.BusinessCode;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * 接口返回对象基类
 * @author admin
 * @date 2017/8/15
 */
public class BaseResult implements Serializable {

    private static final long serialVersionUID = -2457869737632873180L;

    /**
     * 返回业务编码
     */
    private int code = BusinessCode.SUCCESS.getCode();

    /**
     * 返回结果描述
     */
    private String msg = BusinessCode.SUCCESS.getMsg();

    public BaseResult() {
    }

    public BaseResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuccess() {
        return BusinessCode.SUCCESS.getCode() == code;
    }

    public void withError(BusinessCode businessCode) {
        this.code = businessCode.getCode();
        this.msg = businessCode.getMsg();
    }

    public void withError(int code, String errorMsg) {
        this.code = code;
        this.msg = errorMsg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Date getServerTime() {
        return new Date();
    }

    @Override
    public String toString() {
        ValueFilter valueFilter = new ValueFilter() {

            @Override
            public Object process(Object object, String name, Object value) {
                if (object instanceof List) {
                    return ((List<?>) object).size();
                }
                if (value instanceof List) {
                    return "[size=" + ((List<?>) value).size() + "]";
                }
                return value;
            }
        };

        return JSON.toJSONString(this, valueFilter, new SerializerFeature[]{SerializerFeature.WriteMapNullValue,
                SerializerFeature.UseISO8601DateFormat});
    }

}
